import SitePoolSelector from '@/components/SitePoolSelector';
import request from '@/request';
import { IPoolBasicRangeSearchParams } from '@/request/sheet/typing';
import { formatDate, formatPoolNos } from '@/utils/format';
import { flatRecordRes } from '@/utils/record';
import exportTableToExcel from '@/utils/sheet/exportXlsx';
import { Button, Form, Input, Modal, Popconfirm, Space, Table,DatePicker,message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

const { RangePicker } = DatePicker;

interface ISheetData {
  // 记录日期
  date: string;
  // 上报日期
  reportDate: string;
  // 上报人
  reporter: string;
  // 塘号
  poolNo: string;
  //气温
  temperature: number;
  //风向
  wind: string;
  //风力
  scale: number;
  //晴雨状况
  weather: string;
}

const MeteorologyRecord = () => {
  const [showLoading, setShowLoading] = useState(false);
  const [sheetData, setSheetData]: [ISheetData[], any] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [dateRange, setDateRange]: [string[], any] = useState([
    // 默认当天前十五天数据
    dayjs().subtract(14, 'day').format('YYYY-MM-DD'),
    dayjs().format('YYYY-MM-DD'),
  ]);
  useEffect(() => {
    setShowLoading(true);
    request.record
      .getMeteorologyRecordData({ date: dateRange })
      .then((res) => {
        const sheetData: ISheetData[] = [];
        for (let i = 0; i < res.data.length; i++) {
          const item = flatRecordRes(res.data[i]);
          item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
          sheetData.push(item);
        }
        sheetData.sort((a, b) => {
          return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
        });
        setSheetData(sheetData);
      })
      .finally(() => setShowLoading(false));
  }, []);
//以下为新增气象记录
const [form] = Form.useForm();
function handleCreate() {
  setConfirmLoading(true);
  
  form.validateFields().then((res: {  
    poolNo: string;
    userId:string;
    temperature:number;
    wind:string;
    scale:number;
    weather:string;
    date: string;
    }) => {  
    request.record.addMeteorologyRecordData({ ...res}).then((res) => {
      if (res.status === 200) {
       message.success('新增成功',2);
       // 添加成功后，重新获取数据
    setShowLoading(true);
    request.record
      .getMeteorologyRecordData({ date: dateRange })
      .then((res) => {
        const sheetData: ISheetData[] = [];
        for (let i = 0; i < res.data.length; i++) {
          const item = flatRecordRes(res.data[i]);
          item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
          sheetData.push(item);
        }
        sheetData.sort((a, b) => {
          return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
        });
        setSheetData(sheetData);
      })
      .finally(() => setShowLoading(false));
      } else if (res.status === 201) {
        message.error(res.statusText, 2);
      }else{
        message.error('新增失败！', 2);
      }
    });
  });
  setConfirmLoading(false);
  setModalOpen(false);
 
  }
//以上为新增气象记录
  const SearchBar: React.FC = () => {
    const onFinish = (values: IPoolBasicRangeSearchParams) => {
      setShowLoading(true);
      const dateArr = values.dateRange.map((value) => {
        return value.format('YYYY-MM-DD');
      });
      let poolNos: string[] = [];
      if (values.sitePool) poolNos = formatPoolNos(values.sitePool);
      request.record
        .getMeteorologyRecordData({ poolNos, date: dateArr })
        .then((res) => {
          const sheetData: ISheetData[] = [];
          for (let i = 0; i < res.data.length; i++) {
            const item = flatRecordRes(res.data[i]);
            item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
            sheetData.push(item);
          }
          sheetData.sort((a, b) => {
            return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
          });
          setSheetData(sheetData);
          setDateRange(dateArr);
        })
        .finally(() => setShowLoading(false));
    };

    return (
      <div>
      <Form name="customized_form_controls" layout="inline" onFinish={onFinish} className="content-box search-bar">
        <SitePoolSelector type="pool" />
        <Form.Item name="dateRange" label="日期" rules={[{ required: true, message: '该项必填' }]}>
          <RangePicker
            disabledDate={(date) => {
              return date && date > dayjs().endOf('day');
            }}
            placeholder={['开始时间', '结束时间']}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
        <Button
          type="primary"
          style={{ backgroundColor: '#18bc69' }}
          onClick={() => exportTableToExcel('medication-record-table', 'medication-record-table')}
        >
          导出
        </Button>
        </Form.Item>
        <Form.Item>
        <Button type="primary" onClick={() => setModalOpen(true)}>
          新增
        </Button>
        </Form.Item>
      </Form>
      <Modal
       title="新增气象记录"
       open={modalOpen}
       onOk={handleCreate}
       confirmLoading={confirmLoading}
       cancelText="取消"
       okText="确认新增"
       onCancel={() => setModalOpen(false)}
     >
       <Form name="addRecord" style={{ padding: '20px' }} form={form}>
         <Form.Item label="塘号" name="poolNo" rules={[{ required: true, message: '塘号为空' }]}>
           <Input placeholder="请输入塘号" allowClear={true} />
         </Form.Item>
         <Form.Item label="上报人" name="userId" rules={[{ required: true, message: '上报人为空' }]}>
           <Input placeholder="请输入用户名" allowClear={true} />
         </Form.Item>
         <Form.Item label="气温" name="temperature" rules={[{ required: true, message: '气温为空' }]}>
          <Input placeholder="请输入气温" allowClear={true} type="number" />
         </Form.Item>
         <Form.Item label="风向" name="wind" rules={[{ required: true, message: '风向为空' }]}>
          <Input placeholder="请输入风向" allowClear={true} />
         </Form.Item>
         <Form.Item label="风力" name="scale" rules={[{ required: true, message: '风力为空' }]}>
          <Input placeholder="请输入风力" allowClear={true} type="number" />
         </Form.Item>
         <Form.Item label="晴雨情况" name="weather" rules={[{ required: true, message: '晴雨情况为空' }]}>
          <Input placeholder="请输入晴雨情况" allowClear={true} />
         </Form.Item>
         <Form.Item
           label="工作日期"
           name="date"
           rules={[{ required: true, message: '用药日期为空' }]}
         >
            <DatePicker format="YYYY-MM-DD" value-Format="YYYY-MM-DD" />
         </Form.Item>
       </Form>
     </Modal>
     </div>
    );
  };

  const TableContainer = () => {
    const columns: ColumnsType<ISheetData> = [
      {
        title: '塘号',
        dataIndex: 'poolNo',
        key: 'poolNo',
        align: 'center',
        fixed: 'left',
        className: 'first-column',
      },
      {
        title: '上报人',
        dataIndex: 'reporter',
        key: 'reporter',
        align: 'center',
      },
      {
        title: '发生日期',
        dataIndex: 'date',
        key: 'date',
        align: 'center',
        render: (value) => formatDate(value),
      },
      {
        title: '气温',
        dataIndex: 'temperature',
        key: 'temperature',
        align: 'center',
      },
      {
        title: '风向',
        dataIndex: 'wind',
        key: 'wind',
        align: 'center',
      },
      {
        title: '风力',
        dataIndex: 'scale',
        key: 'scale',
        align: 'center',
      },
      {
        title: '晴雨状况',
        dataIndex: 'weather',
        key: 'weather',
        align: 'center',
      },
      {
        title: '上报日期',
        dataIndex: 'reportDate',
        key: 'reportDate',
        align: 'center',
        render: (value) => formatDate(value),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        align: 'center',
        render: (_, record: ISheetData) => (
          <Space className="operation">
            <a className="operation-item edit" onClick={() => handleEdit(record)}>
              修改
            </a>
            <Popconfirm title="确认删除该条数据？" onConfirm={() => handleDelete(record)}>
              <a style={{ color: 'red' }}>删除</a>
            </Popconfirm>
          </Space>
        ),
      },
    ];
    function handleDelete(record: ISheetData) {
      // 从record对象中获取poolNo和date
      const { poolNo, date } = record;

  // 发送请求以删除数据
      request.record
      .deleteMeteorologyRecordData({poolNo, date}).then((res) => {
        if (res.status === 200) {
          // 删除成功后，更新本地状态
        setSheetData((prevData) =>
          prevData.filter((item) => item.poolNo !== poolNo || item.date !== date)
        );
        }
        setShowLoading(false);
      });
      message.success({
        duration: 2,
        content: '删除成功',
      });
    }
 // 此处为修改气象记录
      const layout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      };   
      function convertDateFormat(dateString) {
        // 假设输入格式为 MM/DD/YYYY
        const parts = dateString.split('/');
        // 转换为 YYYY-MM-DD 格式
        return `${parts[0]}-${parts[1]}-${parts[2]}`;
      }   
      const [form] = Form.useForm();
      const [editModalOpen, setEditModalOpen] = useState(false);
      const [editingRecord, setEditingRecord]: [ISheetData[], any] = useState([]);
      const handleEdit = (record: ISheetData) => {
      setEditModalOpen(true);
      setEditingRecord(record);
      };
      const EditModal = (props: { record: ISheetData}) => {
      const { record } = props;
      function handleEditSubmit() {
        setConfirmLoading(true);
        form.validateFields().then((res) => {
          request.record
          .editMeteorologyRecordData({poolNo: res.poolNo, temperature:res.temperature,
            wind:res.wind,
            scale:res.scale,
            weather:res.weather,
            date: res.date})
          .then((res) => {
            if (res.status === 200) {
              message.success('修改成功', 2);
                // 添加成功后，重新获取数据
            
              request.record
                .getMeteorologyRecordData({ date: dateRange })
                .then((res) => {
                  const sheetData: ISheetData[] = [];
                  for (let i = 0; i < res.data.length; i++) {
                    const item = flatRecordRes(res.data[i]);
                    item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
                    sheetData.push(item);
                  }
                  sheetData.sort((a, b) => {
                    return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
                  });
                  setSheetData(sheetData);
                  
                })
            } else message.error('修改失败', 2);
          })
          .finally(() => {
            setConfirmLoading(false);
            setEditModalOpen(false);
          
          });
        });
      }
      return (
      <Modal
          title="修改气象记录"
          open={editModalOpen}
          onOk={handleEditSubmit} // 处理编辑提交的方法
          confirmLoading={confirmLoading}
          cancelText="取消"
          okText="确认修改"
          onCancel={() => {
            setEditModalOpen(false);
          }}
        >
        <Form
              style={{ padding: '20px' }}
              {...layout}
              wrapperCol={{ span: 18 }}
              form={form}
              name="editImmunication"
              autoComplete="off"
              initialValues={{ items: [{}] }}
            >          
          <Form.Item initialValue={record.poolNo} label="塘号" name="poolNo" >
            <Input disabled />
          </Form.Item>
          <Form.Item initialValue={record.reporter} label="上报人" name="userId">
                <Input disabled />
          </Form.Item>
          <Form.Item
          label="记录日期"
          name="date"
          initialValue={convertDateFormat(new Date(record.date).toLocaleString('zh-TW', { year: 'numeric', month: '2-digit', day: '2-digit' }))}
        >
              <Input disabled />
        </Form.Item>
        <Form.Item label="气温" initialValue={record.temperature} name="temperature" rules={[{ required: true, message: '气温为空' }]}>
          <Input placeholder="请输入气温" allowClear={true} type="number" />
         </Form.Item>
         <Form.Item label="风向" initialValue={record.wind} name="wind" rules={[{ required: true, message: '风向为空' }]}>
          <Input placeholder="请输入风向" allowClear={true} />
         </Form.Item>
         <Form.Item label="风力" initialValue={record.scale} name="scale" rules={[{ required: true, message: '风力为空' }]}>
          <Input placeholder="请输入风力" allowClear={true} type="number" />
         </Form.Item>
         <Form.Item label="晴雨情况" initialValue={record.weather} name="weather" rules={[{ required: true, message: '晴雨情况为空' }]}>
          <Input placeholder="请输入晴雨情况" allowClear={true} />
         </Form.Item>
        </Form>
      </Modal>
      );
      };
// 此上为修改气象记录
    return (
      <div className="content-box">
        <Table
          dataSource={sheetData}
          bordered
          pagination={{ pageSize: 1000 }}
          size="small"
          columns={columns}
          id="feed-record-table"
          rowKey={'key'}
          title={() => {
            return `总共匹配到：${sheetData.length}条数据，数据自${dateRange[0]}算起，到${dateRange[1]}。`;
          }}
          loading={showLoading}
        />
        <EditModal record={editingRecord} />
      </div>
    );
  };

  return (
    <div>
      <SearchBar />
      <TableContainer />
    </div>
  );
};
export default MeteorologyRecord;
